//
//  pianosynth.m
//  pianosynth
//
//  Created by Tu Le on 11/24/16.
//  Copyright © 2016 Tu Le. All rights reserved.
//

#import "pianosynth.h"

@implementation pianosynth

- (id)initWithSoundFont:(NSString *)pathToSoundFont
{
    self = [super init];
    if (self) {
        NSURL *url = [NSURL URLWithString:pathToSoundFont];
        NSError *error = nil;
        
        engine = [[AVAudioEngine alloc] init];
        sampler = [[AVAudioUnitSampler alloc] init];
        [engine attachNode:sampler];
        [engine connect:sampler to:[engine outputNode] format:nil];
        [engine startAndReturnError:nil];
        BOOL b = [sampler loadSoundBankInstrumentAtURL:url program:0 bankMSB:kAUSampler_DefaultMelodicBankMSB bankLSB:kAUSampler_DefaultBankLSB error:&error];
        if (!b)
        {
            NSLog(@"%@", error);
        }
        else
        {
            [sampler sendProgramChange:0 bankMSB:kAUSampler_DefaultMelodicBankMSB bankLSB:kAUSampler_DefaultBankLSB onChannel:0];
        }
    }
    return self;
}

-(void)Stop
{
    [engine stop];
}

-(void)SendMsg:(int)msg
{
    int status = msg & 0xFF;
    int note = (msg >> 8) & 0xFF;
    int velocty = (msg >> 16) & 0xFF;
    if (velocty != 0)
        [sampler startNote:note withVelocity:velocty onChannel:(status ^ 0x90)];
    else
        [sampler stopNote:note onChannel:(status ^ 0x80)];
}

@end

static pianosynth *sharedInstance = nil;

extern "C"
{
    void _Start(const char *pathToSoundFont)
    {
        if (sharedInstance == nil)
            sharedInstance = [[pianosynth alloc] initWithSoundFont:[NSString stringWithUTF8String:pathToSoundFont]];
    }
    
    void _Write(int msg)
    {
        if (sharedInstance != nil)
            [sharedInstance SendMsg:msg];
    }
    
    void _Stop()
    {
        if(sharedInstance != nil)
            [sharedInstance Stop];
    }
}
